<template>
	<view class="coupon-wrap">
		<view class="tab-content">
			<u-tabs :list="list" :scrollable="false" :current="active" lineColor="#CF1A1B" lineWidth="90" lineHeight="4"
				:activeStyle="{color: '#CF1A1B'}" :inactiveStyle="{color: 'rgba(0,0,0,0.65)'}" itemStyle="height: 44px;"
				@change="handleChange">
			</u-tabs>
		</view>
		<view v-if="couponList.length == 0" class="empty">
			<image src="../../../static/empty.png"></image>
			<text>无数据</text>
		</view>
		<u-checkbox-group v-model="checkedData" placement="column" size="40" iconSize="30">
			<view class="coupon-list">
				<view class="coupon-item" v-for="item in couponList" :key="item.id" @click="onClickCoupon(item)">
					<view class="coupon-item-left">
						<image class="bg"
							:src="active == 0 ?'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/order/bg_yhq_default.png':'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/order/bg_yhq_disable.png'">
						</image>
						<view class="coupon-price-info">
							<view>
								<view class="coupon-price">￥<text>{{ item.denomination }}</text></view>
							</view>
						</view>
					</view>
					<view class="coupon-item-right">
						<image class="bg"
							src="https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/order/bg_yhq.png">
						</image>
						<view class="coupon-detial">
							<view>
								<view class="title">
									<u-tag :text="item.couponTypeStr" type="error" plain size="mini"></u-tag>
									<text class="ml">{{ item.displayName || '' }}</text>
								</view>
								<view class="type">使用范围：<text
										class="fc">{{ item.commodityType === '0' ? '全部轮胎' : '指定轮胎'}}</text></view>
								<view class="date">有效期至：<text
										class="fc">{{ item.couponEndTime ? item.couponEndTime.slice(0,11) : '' }}</text>
								</view>
								<!-- <view class="dec">• 详细说明：<text class="fc">{{ item.displayName || '' }}</text></view> -->
							</view>
							<view class="checkbox" v-if="active == 0">
								<u-checkbox :key="item.id" :label="item.id" :name="item.id" size="40" shape="circle"
									labelColor="#fff" labelSize="2">
								</u-checkbox>
							</view>
							<view class="status">
								    <image class="img" v-if="item.couponStatus == 1" src="https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/coupon_used.png" mode="aspectFit"></image>
									<image class="img" v-if="item.couponStatus == 2" src="https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/coupon_used.png" mode="aspectFit"></image>
									<image class="img" v-if="item.couponStatus == 3" src="https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/coupon_past.png" mode="aspectFit"></image>
							</view>
						</view>
					</view>
				</view>
				<u-loadmore :status="status" :loading-text="loadingText" :loadmore-text="loadmoreText" fontSize="16"
					height="50" :nomore-text="nomoreText" />
			</view>
		</u-checkbox-group>

		<view class="coupon-bottom">
			<u-button type="primary" @click="onConfirm">确定</u-button>
		</view>

		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'

	export default {
		name: "selectCoupon",
		data() {
			return {
				active: 0,
				checkedData: [],
				couponStatusList: ['0'],
				list: [{
					name: '可用优惠卷',
				}, {
					name: '不可用优惠卷',
				}],
				couponList: [],
				pageNum: 1,
				total: 0,
				emptyVisible: false,
				status: 'loadmore',
				loadingText: '努力加载中',
				loadmoreText: '',
				nomoreText: '没有更多数据了',

				// 轮胎商品列表
				tyreGoodsList: [],
				// 轮胎商品id
				tyreGoodsIds: [],
				// 轮胎商品总数
				tyreGoodsNumber: 0,
				// 轮胎商品总金额
				tyreGoodsTotal: 0,
				// 订单(除优惠券以外)待优惠金额（使用除优惠券以外其他减扣方式之后的订单应付金额）
				unpricedAmount: 0,
			};
		},
		computed: {
			...mapState('user', ['userInfo']),
			// 选择的优惠券列表
			selectedCouponList() {
				return this.checkedData.map(checkedId => {
					return this.couponList.find(item => item.id === checkedId)
				})
			}
		},
		methods: {
			handleChange(val) {
				this.active = val.index
				this.couponList = []
				this.pageNum = 1
				this.showMore = false
				if (val.index == 0) {
					this.couponStatusList = ['0']
				} else {
					this.couponStatusList = ['1', '2','3']
				}
				this.getCoupon()
			},

			// 点击优惠券
			onClickCoupon(coupon) {
				// 当前优惠券在已选优惠券列表索引
				const index = this.checkedData.findIndex(item => item === coupon.id)
				// 已选优惠券总面额
				const couponTotal = this.selectedCouponList.reduce((acc, cur) => (acc + cur.denomination), 0)

				if (index > -1) {
					// 取消选择
					this.checkedData.splice(index, 1)
					this.couponList.forEach(item => item.disabled = false)
				} else {
					if (this.checkedData.length === this.tyreGoodsNumber) {
						// 优惠券数量超出优惠商品数量
						this.$refs.uToast.show({
							message: '优惠券数量超出优惠商品数量',
							position: 'top'
						})
					} else if (couponTotal >= this.tyreGoodsTotal || couponTotal >= this.unpricedAmount) {
						// 优惠券面额超出优惠商品总额或待优惠订单金额
						this.$refs.uToast.show({
							message: '当前已是最大优惠',
							position: 'top'
						})
					} else {
						this.checkedData.push(coupon.id)
					}
				}
			},

			// 提交
			async onConfirm() {
				const tyreGoodsList = this.tyreGoodsList.map(item => ({
					goodsId: item.goodsId,
					quantity: item.quantity
				}))
				// 获取优惠券减免金额
				const {
					datas
				} = await this.$request({
					url: '/api-order/car-owner-order/calculateOrderMoney',
					data: {
						couponIds: this.checkedData,
						goodsContext: tyreGoodsList,
					}
				})
				// 减免金额
				const reductionAmount = datas ? datas.couponDiscountMoney : 0
				// 选择的优惠券id列表
				const selectedCoupons = datas ? datas.usedCoupons.map(item => item.couponId) : []

				const eventChannel = this.getOpenerEventChannel()
				eventChannel.emit('selectCoupon', {
					reductionAmount,
					selectedCoupons
				})
				uni.navigateBack()
			},

			// 获取优惠券
			async getCoupon(data) {
				this.status = 'loading'
				try {
					this.$request({
						method: 'post',
						url: '/marketing-center/distribution/listByAPP',
						data: {
							pageSize: 10,
							couponStatusList: this.couponStatusList,
							pageNum: this.pageNum,
							goodIds: this.tyreGoodsIds,
							userId: this.userInfo.id
						}
					}).then(res => {
						this.couponList = this.couponList.concat(res.datas.data)
						this.total = res.datas.count
						this.status = 'loadmore'
					})
				} catch (err) {
					//
				}
				uni.hideLoading()
				uni.stopPullDownRefresh();
			},
		},
		onLoad() {
			uni.showLoading({
				title: '加载中...'
			})
			this.couponStatusList = ['0']
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('initCoupon', (data) => {
				this.checkedData = data.selectedCouponIds
				this.tyreGoodsList = data.tyreGoodsList
				data.tyreGoodsList.forEach(item => {
					this.tyreGoodsIds.push(item.goodsId)
					this.tyreGoodsNumber += item.quantity
					this.tyreGoodsTotal += item.quantity * item.price
				})
				this.unpricedAmount = data.unpricedAmount
				this.getCoupon()
			})
		},
		onReachBottom() {
			if (this.couponList.length >= this.total) {
				this.status = 'nomore'
				return;
			}
			this.pageNum += 1
			this.getCoupon()
		},
		onPullDownRefresh() {
			this.couponList = []
			this.pageNum = 1
			this.getCoupon();
		},
	}
</script>

<style lang="scss" scoped>
	.coupon-wrap {
		height: 100vh;

		/deep/ .u-tabs__wrapper__nav__line {
			margin-left: 16px;
		}

		/deep/ .u-tabs__wrapper__nav__item {
			padding: 0;
		}

		.tab-content {
			background: #fff;
			z-index: 99;
			position: fixed;
			width: 100%;
			top: 0;
		}

		.coupon-list {
			display: flex;
			justify-content: center;
			flex-wrap: wrap;
			padding-bottom: 180rpx;
			margin-top: 90rpx;

			.coupon-item {
				width: 95%;
				background: #fff;
				margin-top: 24rpx;
				display: flex;

				.bg {
					position: absolute;
					z-index: 0;
					left: 0;
					right: 0;
					bottom: 0;
					right: 0;
					width: 100%;
					height: 100%;
				}

				.coupon-item-left {
					width: 232rpx;
					height: 196rpx;
					position: relative;

					.coupon-price-info {
						width: 100%;
						height: 100%;
						display: flex;
						color: #fff;
						flex-wrap: wrap;
						justify-content: center;
						align-items: center;
						position: relative;
						z-index: 2;

						.coupon-price {
							width: 100%;
							font-size: 28px;
							font-weight: bold;
							font-family: 'Source Han Sans CN-Bold';
							text-align: center;
							margin-bottom: 16rpx;
						}

						.coupon-price-dec {
							width: 100%;
							font-size: 12px;
							text-align: center;
						}
					}
				}

				.coupon-item-right {
					flex: 1;
					position: relative;

					.coupon-detial {
						position: relative;
						display: flex;
						flex-wrap: wrap;
						justify-content: flex-start;
						align-items: center;
						z-index: 2;
						padding-left: 32rpx;
						height: 190rpx;

						.checkbox {
							position: absolute;
							right: 20rpx;
							top: 45%;
						}

						.status {
							position: absolute;
							top: 0rpx;
							right: 10rpx;
							height: 100%;
							width: 200rpx;
							z-index: 2;

							.img {
								width: 100%;
								height: 100%;

							}

						}

						.title {
							color: #000;
							font-size: 14px;
							font-weight: 500;
							margin-bottom: 28rpx;
							display: flex;
							justify-content: flex-start;
							align-items: center;

							.ml {
								margin-left: 10rpx;
							}
						}

						.type {
							margin-bottom: 18rpx;
							font-size: 13px;
							color: rgba($color: #000000, $alpha: 0.45);
						}

						.date {
							font-size: 13px;
							color: rgba($color: #000000, $alpha: 0.45);
						}

						.dec {
							font-size: 13px;
							color: rgba($color: #000000, $alpha: 0.45);
						}

						.fc {

							color: rgba($color: #000000, $alpha: 0.65);
						}
					}
				}

			}
		}

		.coupon-bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background: #fff;
			z-index: 5;
			padding: 30rpx 32rpx;
		}

		.load-text {
			text-align: center;
			font-size: 12px;
			margin-top: 16rpx;
			color: rgba($color: #000000, $alpha: 0.45);
		}

		.empty {
			width: 100%;
			height: 80%;
			position: absolute;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			image {
				width: 220px;
				height: 180px;
			}

			text {
				font-size: 30rpx;
				color: rgba(0, 0, 0, 0.45);
				line-height: 30rpx;
			}
		}
	}
</style>
